#include "server.hpp"
#include <time.h>

// unordered_map<uint64_t, con_ptr> conns;
// uint64_t id = 0;
// event_loop base_loop;
// loop_thread_pool *thread_pool;
// void connected(const con_ptr &con) {
//     INFO_LOG("client: %ld connected!", con->get_id());
// }

// void massage(const con_ptr &con, buffer *buf) {
//     INFO_LOG("msg: %s", buf->get_read_pos());
//     buf->move_read_pos(buf->get_readable_size());
//     string echo = "server# echo...";
//     con->send(echo.c_str(), echo.size());
// }

// void disconneted(const con_ptr &con) {
//     INFO_LOG("client: %ld disconnected!", con->get_id());
//     conns.erase(con->get_id());
// }

// void new_connection(int newfd) {
//     con_ptr con = make_shared<connection>(thread_pool->next_loop(), id, newfd); 
//     con->set_connected_callback(bind(connected, placeholders::_1));
//     con->set_handle_messge_callback(bind(massage, placeholders::_1, placeholders::_2));
//     con->set_server_closed_callback(bind(disconneted, placeholders::_1));

//     con->enable_inactive_destroy(5); 
//     con->established();
//     conns.insert({id, con});
//     ++id;
// }


// int main() {
//     srand(time(nullptr));  // for random port number
//     thread_pool = new loop_thread_pool(&base_loop);
//     thread_pool->set_thread_count(2);
//     thread_pool->create();
//     acceptor acpt(&base_loop);
//     acpt.set_acceptor_callback(bind(new_connection, placeholders::_1));
//     acpt.listen();
//     base_loop.start();
//     return 0;
// }

void handle_connected(const con_ptr &con) {
    INFO_LOG("client connected, id = %ld", con->get_id());
}

void handle_msg(const con_ptr &con, buffer *buf) {
    INFO_LOG("msg: %s", buf->get_read_pos());
    buf->move_read_pos(buf->get_readable_size());
    string echo = "server# echo...";
    con->send(echo.c_str(), echo.size());
}

void handle_close(const con_ptr &con) {
    INFO_LOG("client disconnected, id = %ld", con->get_id() );
}

int main() {
    srand(time(nullptr));  // for random port number
    tcp_server server(8080);
    server.enable_inactive_destroy(5);
    server.set_thread_count(2);
    server.set_connected_callback(handle_connected);
    server.set_handle_messge_callback(handle_msg);
    server.set_closed_callback(handle_close);
    server.start();  
    return 0;
}